package svc

import (
	"database/sql"

	"mall/common/modelx"
	"mall/service/backend/repository"
	"mall/service/backend/rpc/internal/config"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)

type ServiceContext struct {
	Config config.Config

	BackendMenu       repository.BackendMenuRepository
	BackendPermission repository.BackendPermissionRepository
	BackendRole       repository.BackendRoleRepository
	BackendUser       repository.BackendUserRepository
	MemberLevel       repository.MemberLevelRepository
	Recommendation    repository.RecommendationRepository
	BizRedis          *redis.Redis
	DB                *sql.DB
	SysApi            repository.SysApiRepository
	SysMenu           repository.SysMenuRepository
	SysRole           repository.SysRoleRepository
	SysPosition       repository.SysPositionRepository
	SysUser           repository.SysUserRepository
	SysToken          repository.SysTokenRepository

	Banner        repository.BannerRepository
	Section       repository.SectionRepository
	SearchKeyword repository.SearchKeywordRepository
}

func NewServiceContext(c config.Config) *ServiceContext {
	db, err := modelx.NewMysqlConn(c.Mysql.DataSource)
	if err != nil {
		logx.Must(err)
	}

	rds := redis.MustNewRedis(c.BizRedis)

	return &ServiceContext{
		Config:            c,
		BackendMenu:       repository.NewBackendMenuRepository(c.Mysql.DataSource, c.CacheRedis),
		BackendPermission: repository.NewBackendPermissionRepository(c.Mysql.DataSource, c.CacheRedis),
		BackendRole:       repository.NewBackendRoleRepository(c.Mysql.DataSource, c.CacheRedis),
		BackendUser:       repository.NewBackendUserRepository(c.Mysql.DataSource, c.CacheRedis),
		MemberLevel:       repository.NewMemberLevelRepository(c.Mysql.DataSource, c.CacheRedis),
		Recommendation:    repository.NewRecommendationRepository(c.Mysql.DataSource, c.CacheRedis),
		BizRedis:          rds,
		DB:                db,
		SysApi:            repository.NewSysApiRepository(db, c.CacheRedis),
		SysMenu:           repository.NewSysMenuRepository(db, c.CacheRedis),
		SysRole:           repository.NewSysRoleRepository(db, c.CacheRedis),
		SysPosition:       repository.NewSysPositionRepository(db, c.CacheRedis),
		SysUser:           repository.NewSysUserRepository(db, c.CacheRedis),
		SysToken:          repository.NewSysTokenRepository(db, c.CacheRedis),

		Banner:        repository.NewBannerRepository(db, c.CacheRedis),
		Section:       repository.NewSectionRepository(db, c.CacheRedis),
		SearchKeyword: repository.NewSearchKeywordRepository(db, c.CacheRedis),
	}
}
